import express, { json, urlencoded } from "express";
// 跨域
import cors from "cors";
// 日志
import morgan from "morgan";
import router from "./router/index.js";
import { errorHandler } from "./middleware/errorHandler.js";
import { initializeWebSocket } from "./websocket/chatHandler.js";
import http from "http";

const app = express();

// 解析请求体 json格式
app.use(json());
// 解析请求体 urlencoded格式
app.use(urlencoded({ extended: true }));
app.use("/v1.0", router);
// 跨域
app.use(cors());
app.use(morgan("dev"));
app.use(errorHandler);

// 创建 HTTP 服务器
const server = http.createServer(app);
// 初始化 WebSocket
initializeWebSocket(server);

const PORT = process.env.PORT || 3000;
// 使用 server 而不是 app 来监听端口
server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
